import React from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Platform,
  Dimensions,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Icon from 'react-native-vector-icons/Ionicons';
import DeviceInfo from 'react-native-device-info';
import { COLORS } from '../styles/constants';

/**
 * 自定义TabBar组件
 * 专门解决虚拟按钮遮挡问题
 */
const CustomTabBar = ({ state, descriptors, navigation }) => {
  const insets = useSafeAreaInsets();
  const [deviceInfo, setDeviceInfo] = React.useState(null);

  React.useEffect(() => {
    const getDeviceInfo = async () => {
      if (Platform.OS === 'android') {
        try {
          const brand = await DeviceInfo.getBrand();
          const model = await DeviceInfo.getModel();
          setDeviceInfo({ brand, model });
        } catch {
          // Ignore device info fetch errors
        }
      }
    };
    getDeviceInfo();
  }, []);

  // 计算底部安全边距
  const getBottomSafeArea = () => {
    if (Platform.OS === 'ios') {
      // iOS使用系统提供的安全区域
      return insets.bottom;
    }

    // Android设备处理
    const brand = deviceInfo?.brand?.toLowerCase() || '';
    const model = deviceInfo?.model?.toLowerCase() || '';

    // 三星和其他默认品牌直接使用系统安全区域，不添加额外高度
    const isProblematicBrand =
      brand.includes('vivo') ||
      brand.includes('oppo') ||
      brand.includes('oneplus') ||
      brand.includes('xiaomi') ||
      brand.includes('redmi') ||
      model.includes('iqoo');

    // 如果不是问题品牌，直接返回系统安全区域
    if (!isProblematicBrand) {
      return insets.bottom;
    }

    // 仅对有虚拟按键遮挡问题的品牌做特殊处理
    const screenData = Dimensions.get('screen');
    const windowData = Dimensions.get('window');
    const possibleNavHeight = screenData.height - windowData.height;

    let safeBottom = Math.max(insets.bottom, possibleNavHeight, 12);

    if (
      brand.includes('vivo') ||
      brand.includes('oppo') ||
      brand.includes('oneplus')
    ) {
      safeBottom = Math.max(safeBottom, 30);
      if (model.includes('iqoo')) {
        safeBottom = Math.max(safeBottom, 36);
      }
    } else if (brand.includes('xiaomi') || brand.includes('redmi')) {
      safeBottom = Math.max(safeBottom, 28);
    }

    return safeBottom;
  };

  const bottomSafeArea = getBottomSafeArea();
  const baseHeight = 60;
  const containerHeight = baseHeight + bottomSafeArea;
  const internalPaddingBottom = bottomSafeArea;

  return (
    <View style={[styles.container, { height: containerHeight }]}>
      <View style={[styles.tabBar, { paddingBottom: internalPaddingBottom }]}>
        {state.routes.map((route, index) => {
          const { options } = descriptors[route.key];
          const label =
            options.tabBarLabel !== undefined
              ? options.tabBarLabel
              : options.title !== undefined
              ? options.title
              : route.name;

          const isFocused = state.index === index;

          const onPress = () => {
            const event = navigation.emit({
              type: 'tabPress',
              target: route.key,
              canPreventDefault: true,
            });

            if (!isFocused && !event.defaultPrevented) {
              navigation.navigate(route.name);
            }
          };

          const onLongPress = () => {
            navigation.emit({
              type: 'tabLongPress',
              target: route.key,
            });
          };

          // 图标映射
          let iconName = 'ellipse';
          if (route.name === 'Home') {
            iconName = isFocused ? 'home' : 'home-outline';
          } else if (route.name === 'Profile') {
            iconName = isFocused ? 'person' : 'person-outline';
          }

          return (
            <TouchableOpacity
              key={route.key}
              accessibilityRole="button"
              accessibilityState={isFocused ? { selected: true } : {}}
              accessibilityLabel={options.tabBarAccessibilityLabel}
              testID={options.tabBarTestID}
              onPress={onPress}
              onLongPress={onLongPress}
              style={styles.tab}
            >
              <Icon
                name={iconName}
                size={24}
                color={isFocused ? COLORS.primary : COLORS.text.quaternary}
              />
              <Text
                style={[
                  styles.tabLabel,
                  { color: isFocused ? COLORS.primary : COLORS.text.quaternary },
                ]}
              >
                {label}
              </Text>
            </TouchableOpacity>
          );
        })}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: COLORS.background.card,
    borderTopWidth: 1,
    borderTopColor: COLORS.border.light,
    // 使用绝对定位确保在最顶层
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    zIndex: 1000,
  },
  tabBar: {
    flexDirection: 'row',
    height: 49,
    paddingTop: 5,
  },
  tab: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  tabLabel: {
    fontSize: 12,
    fontWeight: '500',
    marginTop: 2,
  },
});

export default CustomTabBar;
